﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace AsyncServer
{
    public class AsyncTCPServer
    {
        public void Start()
        {
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6065);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(ipe);
            socket.Listen(10);
            AsyncAccept(socket);
        }


        private void AsyncAccept(Socket socket)
        {
            socket.BeginAccept(t =>
            {
                Socket client = socket.EndAccept(t);
                Console.WriteLine(string.Format("客户端{0}请求连接。。。", client.RemoteEndPoint));
                AsyncSend(client, "服务器收到连接请求");
                AsyncSend(client, string.Format("欢迎你{0}", client.RemoteEndPoint));
                AsyncReceive(client);
            }, null);

        }

        private void AsyncReceive(Socket socket)
        {
            byte[] data = new byte[1024];
            try
            {
                socket.BeginReceive(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    int length = socket.EndReceive(asyncResult);
                    Console.WriteLine(string.Format("客户端发送消息：{0}", Encoding.UTF8.GetString(data)));
                }, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void AsyncSend(Socket client, string p)
        {
            if (client == null || string.IsNullOrEmpty(p))
            {
                return;
            }

            byte[] data = new byte[1024];
            data = Encoding.UTF8.GetBytes(p);
            try
            {
                client.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    int length = client.EndSend(asyncResult);
                    Console.WriteLine(string.Format("服务器发出消息：{0}", p));
                }, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

    }
}
